const express = require("express");
const app = express();


const { expressjwt:jwt } = require("express-jwt")
const { corsOptions, setTokenOptions, port } = require("./utils/config")

const fileUpload = require("express-fileupload");


// 引入跨域插件
// 解决跨域
const cors = require('cors');
app.use(cors({
    origin:'*',
})); // corsOptions
const NoTokenAuth = ["/users/login","/register","/wxLogin",]

const bodyParser = require('body-parser');
app.use(bodyParser.json());      //配置这两行代码
// 在路由之前配置解析token的中间件



app.use(express.urlencoded({extended:false}))





                    


app.use(fileUpload());



//验证token是否过期并规定那些路由不需要验证
app.use(jwt({
    
    secret:setTokenOptions.jwtSecretKey,
    algorithms:['HS256']}).unless({
       path:NoTokenAuth
   }))


// 错误处理
app.use((err, req, res, next) => {
    if (err && err.error && err.error.isJoi) {
        // 如果是 Joi 验证错误
        const errors = err.error.details.map(detail => detail.message);
        return res.status(400).json({ code: 400, errors });
    }
    // token 失效
    if(err.status == 401 && err.code == 'invalid_token'){
       return res.send({ code: err.status, msg: '登录过期,请重新登录' })
    }
    // 其他错误
    // return res.status(500).json({ code: 500, msg: 'Internal server error' });
});







app.use((req,res,next)=>{
    
    res.output = function (err,code=403,data){
        // 这次错误是由 token 解析失败导致的
        //if(err.status ==='401'){ return res.send({code:1000,msg:"登录过期,请重新登录"}) }
        res.send({code,msg:err instanceof Error ? err.message : err,data})
    }
    next()
})





// 导入并使用登录,注册,或者用户信息的路由模块
const authRouter = require("./router/auth")
const upload = require("./router/upload")
// ws
const wss = require('./websocket/index')
app.use(authRouter)
app.use(upload)







app.listen(port,()=>{
    console.log(`Express server running at 127.0.0.1:${port}`)
 })
